import React, { useState, useRef, useEffect } from 'react';
import { motion, useScroll, useTransform } from 'framer-motion';
import { Typography } from 'antd';
import { ChevronRight, Check, Database, Edit3, Layers, Sliders, Film, Save } from 'lucide-react';

const { Title, Text } = Typography;

interface Step {
    id: number;
    title: string;
    description: string;
    color: string;
    icon: React.ReactNode;
}

const ScrollingTutorial: React.FC = () => {
    const [activeStep, setActiveStep] = useState<number>(0);
    const stepRefs = useRef<(HTMLDivElement | null)[]>([]);
    const isScrollingProgrammatically = useRef(false);
    const scrollTimeout = useRef<NodeJS.Timeout | null>(null);

    const { scrollYProgress } = useScroll();
    const opacity = useTransform(scrollYProgress, [0, 0.1], [0, 1]);

    const steps: Step[] = [
        {
            id: 1,
            title: '项目管理',
            description: '在项目管理页面查看、创建和编辑您的视频项目',
            color: '#6b5ce7',
            icon: <Database size={32} />,
        },
        {
            id: 2,
            title: '进入编辑',
            description: '点击对应项目进入专业的视频编辑界面',
            color: '#ff7a45',
            icon: <Edit3 size={32} />,
        },
        {
            id: 3,
            title: '添加素材',
            description: '在轨道上添加视频、音频、文字等素材，通过拖拽编辑视频内容',
            color: '#1890ff',
            icon: <Layers size={32} />,
        },
        {
            id: 4,
            title: '素材配置',
            description: '点击对应素材，在右侧表单中进行详细配置，如动画特效、转场效果等',
            color: '#722ed1',
            icon: <Sliders size={32} />,
        },
        {
            id: 5,
            title: '生成视频',
            description: '点击生成视频按钮，预览编辑效果，调整细节',
            color: '#52c41a',
            icon: <Film size={32} />,
        },
        {
            id: 6,
            title: '保存项目',
            description: '完成编辑后，点击保存按钮，保存您的视频项目',
            color: '#13c2c2',
            icon: <Save size={32} />,
        },
    ];

    useEffect(() => {
        const observer = new IntersectionObserver(
            (entries) => {
                // 【修改点 2】如果正在程序化滚动，则忽略 observer 的所有更新
                if (isScrollingProgrammatically.current) return;

                // 找到所有正在交叉的条目
                const intersectingEntries = entries.filter((entry) => entry.isIntersecting);

                // 如果有正在交叉的条目，只取最后一个（通常是滚动后最新的那个）
                if (intersectingEntries.length > 0) {
                    const lastIntersectingEntry = intersectingEntries[intersectingEntries.length - 1];
                    const id = Number(lastIntersectingEntry.target.id.replace('step-', ''));
                    setActiveStep(id - 1);
                }
            },
            {
                rootMargin: '-50% 0px -50% 0px', // 使用 rootMargin 让屏幕中心的元素被视为交叉点
                threshold: 0, // 只要一进入中心区域就触发
            }
        );

        stepRefs.current.forEach((ref) => {
            if (ref) observer.observe(ref);
        });

        return () => {
            stepRefs.current.forEach((ref) => {
                if (ref) observer.unobserve(ref);
            });
        };
        // 【修改点 3】添加依赖项，使其更健壮
    }, [steps.length]);

    const handleIndicatorClick = (id: number) => {
        // 【修改点 4】在开始滚动前，设置标志位并清除之前的延时器
        isScrollingProgrammatically.current = true;
        if (scrollTimeout.current) {
            clearTimeout(scrollTimeout.current);
        }

        document.getElementById(`step-${id}`)?.scrollIntoView({
            behavior: 'smooth',
            block: 'center', // 滚动到视口中心
        });

        // 设置一个延时器，在滚动动画结束后（约800毫秒）将标志位重置
        scrollTimeout.current = setTimeout(() => {
            isScrollingProgrammatically.current = false;
        }, 800);
    };

    const handleNextStep = () => {
        if (activeStep < steps.length - 1) {
            handleIndicatorClick(steps[activeStep + 1].id);
        }
    };

    return (
        <div style={{ padding: '40px 0' }}>
            {/* Header section remains the same */}
            <motion.div style={{ opacity }} className="tutorial-header">
                <Title
                    level={2}
                    style={{
                        textAlign: 'center',
                        marginBottom: '40px',
                        color: '#FFFFFF',
                    }}
                >
                    快速上手指南
                </Title>
                <Text
                    style={{
                        display: 'block',
                        textAlign: 'center',
                        maxWidth: '800px',
                        margin: '0 auto 60px',
                        color: '#FFFFFF',
                    }}
                >
                    滚动页面了解如何使用我们的视频编辑工具，每滚动一段距离将显示一个新的教程步骤。
                </Text>
            </motion.div>

            {/* 【修改点 5】为容器添加 scroll-snap-type 以增强滚动体验 */}
            <div className="steps-container" style={{ scrollSnapType: 'y mandatory' }}>
                {steps.map((step, index) => (
                    <motion.div
                        key={step.id}
                        id={`step-${step.id}`}
                        ref={(el) => (stepRefs.current[index] = el)}
                        initial={{ opacity: 0, y: 50 }}
                        animate={{
                            opacity: activeStep === index ? 1 : 0.6,
                            y: 0,
                        }}
                        transition={{ duration: 0.5 }}
                        style={{
                            minHeight: '100vh', // 设置为100vh，确保每个步骤占满一屏，更好地配合滚动吸附
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            padding: '40px 20px',
                            scrollSnapAlign: 'center', // 将元素的中心与容器的中心对齐
                        }}
                    >
                        <div
                            style={{
                                maxWidth: '900px',
                                width: '100%',
                                display: 'flex',
                                flexDirection: index % 2 === 0 ? 'row' : 'row-reverse',
                                alignItems: 'center',
                                gap: '40px',
                            }}
                        >
                            <div
                                style={{
                                    flex: 1,
                                    display: 'flex',
                                    flexDirection: 'column',
                                    alignItems: index % 2 === 0 ? 'flex-start' : 'flex-end',
                                    textAlign: index % 2 === 0 ? 'left' : 'right',
                                }}
                            >
                                <div
                                    style={{
                                        display: 'flex',
                                        alignItems: 'center',
                                        marginBottom: '20px',
                                    }}
                                >
                                    <div
                                        style={{
                                            width: '50px',
                                            height: '50px',
                                            borderRadius: '50%',
                                            display: 'flex',
                                            justifyContent: 'center',
                                            alignItems: 'center',
                                            backgroundColor: `${step.color}20`,
                                            color: '#FFFFFF',
                                            fontSize: '24px',
                                            marginRight: index % 2 === 0 ? '16px' : 0,
                                            marginLeft: index % 2 === 0 ? 0 : '16px',
                                        }}
                                    >
                                        {activeStep >= index ? <Check size={24} color="#FFFFFF" /> : step.id}
                                    </div>
                                    <div
                                        style={{
                                            fontSize: '16px',
                                            fontWeight: 'bold',
                                            color: '#FFFFFF',
                                        }}
                                    >
                                        步骤 {step.id}
                                    </div>
                                </div>
                                <Title
                                    level={3}
                                    style={{
                                        marginBottom: '16px',
                                        color: '#FFFFFF',
                                    }}
                                >
                                    {step.title}
                                </Title>
                                <Text
                                    style={{
                                        fontSize: '18px',
                                        color: '#FFFFFF',
                                        lineHeight: '1.8',
                                        marginBottom: '24px',
                                    }}
                                >
                                    {step.description}
                                </Text>
                                {activeStep === index && (
                                    <motion.div
                                        initial={{ opacity: 0, x: -20 }}
                                        animate={{ opacity: 1, x: 0 }}
                                        transition={{ duration: 0.5 }}
                                        className="next-hint"
                                        style={{
                                            display: 'flex',
                                            alignItems: 'center',
                                            color: '#FFFFFF',
                                            fontWeight: 'bold',
                                            cursor: 'pointer',
                                        }}
                                        onClick={() => handleNextStep()}
                                    >
                                        下一步{' '}
                                        <ChevronRight
                                            size={18}
                                            style={{
                                                marginLeft: '8px',
                                                color: '#FFFFFF',
                                            }}
                                        />
                                    </motion.div>
                                )}
                            </div>
                            <div
                                style={{
                                    flex: 1,
                                    height: '300px',
                                    borderRadius: '12px',
                                    overflow: 'hidden',
                                    backgroundColor: `${step.color}10`,
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    boxShadow: '0 10px 30px rgba(0, 0, 0, 0.1)',
                                }}
                            >
                                <div
                                    style={{
                                        fontSize: '80px',
                                        color: step.color,
                                        opacity: 0.5,
                                    }}
                                >
                                    {step.icon}
                                </div>
                            </div>
                        </div>
                    </motion.div>
                ))}
            </div>

            {/* Progress indicator */}
            <div
                style={{
                    position: 'fixed',
                    left: '20px',
                    top: '50%',
                    transform: 'translateY(-50%)',
                    display: 'flex',
                    flexDirection: 'column',
                    gap: '10px',
                    zIndex: 100,
                }}
            >
                {steps.map((step, index) => (
                    <div
                        key={step.id}
                        style={{
                            width: '12px',
                            height: '12px',
                            borderRadius: '50%',
                            backgroundColor: activeStep >= index ? step.color : '#e5e5e5',
                            cursor: 'pointer',
                            transition: 'all 0.3s ease',
                            boxShadow: activeStep === index ? `0 0 0 4px ${step.color}30` : 'none',
                            color: '#FFFFFF',
                        }}
                        // 使用新的点击处理函数
                        onClick={() => handleIndicatorClick(step.id)}
                        title={step.title}
                    />
                ))}
            </div>
        </div>
    );
};

export default ScrollingTutorial;
